use sea_orm::{ConnectOptions, Database, DatabaseConnection};
use std::io;
use std::time::Duration;
use tracing::level_filters::LevelFilter;
use tracing_subscriber::fmt::time::ChronoLocal;
use tracing_subscriber::layer::SubscriberExt;
use tracing_subscriber::util::SubscriberInitExt;
use tracing_subscriber::{Layer, Registry, fmt};

pub mod entity;

/// 获取数据库连接
pub async fn get_connection() -> DatabaseConnection {
    let mut opt = ConnectOptions::new("mysql://root:root@localhost/sea-orm");
    opt.max_connections(20)
        .min_connections(5)
        .connect_timeout(Duration::from_secs(8))
        .acquire_timeout(Duration::from_secs(8))
        .idle_timeout(Duration::from_secs(8))
        .max_lifetime(Duration::from_secs(8))
        .sqlx_logging(true)
        .sqlx_logging_level(log::LevelFilter::Debug);

    let db = Database::connect(opt).await.expect("数据库连接失败");
    match db.ping().await {
        Ok(_) => log::info!("数据库连接成功"),
        Err(e) => panic!("数据库连接失败: {}", e)
    }
    db
}

/// 初始化日志
pub fn init_log() {
    let timer = ChronoLocal::new(String::from("%Y-%m-%d %H:%M:%S"));

    let console_layer = fmt::layer()
        // 自定义数据时间格式
        .with_timer(timer)
        // 线程名
        .with_thread_names(true)
        // 输出到标准的成错误输出
        .with_writer(io::stderr)
        // 只记录INFO及以上级别的日志
        .with_filter(LevelFilter::DEBUG);
    // 注册
    Registry::default().with(console_layer).init();
}
